package tc.alert.tckejisoc.service;


import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Service
public class GeoIPService {
    private final DatabaseReader reader;

    public GeoIPService(DatabaseReader reader) {
        this.reader = reader;
    }


    // 新增方法：判断 IP 类型并进行格式转换
    private String normalizeIP(String ip) {
        try {
            InetAddress ipAddress = InetAddress.getByName(ip);
            if (ipAddress instanceof Inet6Address) {
                // IPv6 地址转换为规范化格式
                return ipAddress.getHostAddress().toLowerCase();
            } else {
                // IPv4 地址直接返回
                return ipAddress.getHostAddress();
            }
        } catch (UnknownHostException e) {
            return null; // 无效 IP
        }
    }
    // 新增方法，用于获取经纬度
    public double[] getLatitudeLongitude(String ip) {
        try {
            ip = normalizeIP(ip);
            InetAddress ipAddress = InetAddress.getByName(ip);

//            // 内网IP检测
//            if (isPrivateIP(ipAddress)) {
//                return null; // 内网IP不返回经纬度
//            }

            CityResponse response = reader.city(ipAddress);
            double latitude = response.getLocation().getLatitude();
            double longitude = response.getLocation().getLongitude();
            return new double[]{latitude, longitude};
        } catch (UnknownHostException e) {
            return null; // 无效IP
        } catch (IOException | GeoIp2Exception e) {
            return null; // 数据库错误
        }
    }
    public String getCountryCode(String ip) {
        try {
            InetAddress ipAddress = InetAddress.getByName(ip);

            // 内网IP检测
            if (isPrivateIP(ipAddress)) {
                return "LAN";
            }

            CityResponse response = reader.city(ipAddress);
            return response.getCountry().getIsoCode();
        } catch (UnknownHostException e) {
            return "INVALID_IP";
        } catch (IOException | GeoIp2Exception e) {
            return "DB_ERROR";
        }
    }

    private boolean isPrivateIP(InetAddress ip) {
        byte[] bytes = ip.getAddress();
        if (bytes.length == 4) { // IPv4
            return (bytes[0] == 10) ||
                    (bytes[0] == (byte) 172 && bytes[1] >= 16 && bytes[1] <= 31) ||
                    (bytes[0] == (byte) 192 && bytes[1] == (byte) 168);
        }
        return ip.isSiteLocalAddress();
    }


}